<template>
  <div class="management">
    <el-form :model="form" ref="customerRef" :rules="userRules" label-width="auto">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="customerName" label="客户姓名">
            <el-input v-model="form.customerName"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="school" label="客户学校">
            <el-input v-model="form.school"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="speciality" label="客户专业">
            <el-input v-model="form.speciality"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="money" label="金额">
            <el-input v-model="form.money" type="number"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="deposit" label="已收定金">
            <el-input v-model="form.deposit"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="completedMoney" label="已收尾款">
            <el-input v-model="form.completedMoney"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="director" label="负责人">
            <el-select v-model="form.director" placeholder="请选择负责人">
              <el-option
                v-for="item in followUpList"
                :key="item.username"
                :label="item.userdename"
                :value="item.userdename"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="followUp" label="跟进人">
            <el-select v-model="form.followUp" placeholder="请选择跟进人">
              <el-option
                v-for="item in directorList"
                :key="item.username"
                :label="item.userdename"
                :value="item.userdename"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="check" label="查重">
            <el-input v-model="form.check"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="thesisTitle" label="论文题目">
            <el-input v-model="form.thesisTitle" type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="customerId" label="客户电话">
            <el-input v-model="form.customerId" type="text"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="difficulty" label="论文难度">
            <el-select v-model="form.difficulty" placeholder="请选择论文难度">
              <el-option label="A" value="A" />
              <el-option label="B" value="B" />
              <el-option label="c" value="c" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="degree" label="学位">
            <el-radio-group v-model="form.degree">
              <el-radio value="带学位">带学位</el-radio>
              <el-radio value="不带学位">不带学位</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="accountPassword" label="账号/密码">
            <el-input v-model="form.accountPassword"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="website" label="网址链接">
            <el-input v-model="form.website"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="reviewTime" label="选题起始/结束时间">
            <el-date-picker
              v-model="form.reviewTime"
              type="daterange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
              size="default"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="headlineTime" label="开题起始/结束时间">
            <el-date-picker
              v-model="form.headlineTime"
              type="daterange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
              size="default"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="firstTime" label="初稿起始/结束时间">
            <el-date-picker
              v-model="form.firstTime"
              type="daterange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
              size="default"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="finalizeTime" label="定稿起始/结束时间">
            <el-date-picker
              v-model="form.finalizeTime"
              type="daterange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
              size="default"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="上传客户文件" prop="filePath"> 
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="http://192.168.112.160:8880/api/commerce/v2/client/upload"
              :headers="headersObj"
              :auto-upload="false"
              :on-success="handleSuccess"
              :on-error="handleError"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleChange"
              :on-remove="handleRemove"
            >
              <el-button type="primary">选择文件</el-button>
              <div class="el-upload__tip">
                最多上传一个文件，如已上传了一个文件，请先删除后才能上传
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="notes" label="客户备注">
            <el-input v-model="form.notes" type="textarea"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" class="form-buttons">
          <el-button type="primary" @click="uploadFile(customerRef)">提交</el-button>
          <el-button @click="cancellClick">取消</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, defineProps, ref,onMounted } from 'vue';
import { ElNotification } from 'element-plus';
import { uploadImg } from "@/api/modules/upload";
import { useUserStore } from "@/stores/modules/user"; // 导入用户状态管理store
import { getUserList } from "@/api/modules/user";
const userStore = useUserStore(); // 获取用户状态管理store实例

// 验证规则
const customerRef = ref()
const headersObj = {
  "Authorization": 'Bearer ' + userStore.token,    // JWT认证，携带token
}
const userRules = reactive({
  customerName: [{ required: true, message: "请输入客户姓名", trigger: "blur" }],
  school: [{ required: true, message: "请输入客户学校", trigger: "blur" }],
  speciality: [{ required: true, message: "请输入客户专业", trigger: "blur" }],
  director: [{ required: true, message: "请选择负责人", trigger: "change" }],
  followUp: [{ required: true, message: "请选择跟进人", trigger: "change" }],
  difficulty: [{ required: true, message: "请选择论文难度", trigger: "change" }],
  reviewTime: [{ required: true, message: "请选择选题起始/结束时间", trigger: "change" }],
  headlineTime: [{ required: true, message: "请选择开题起始/结束时间", trigger: "change" }],
  firstTime: [{ required: true, message: "请选择初稿起始/结束时间", trigger: "change" }],
  finalizeTime: [{ required: true, message: "请选择定稿起始/结束时间", trigger: "change" }],
  customerId: [{ required: true, message: "请输入客户电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: 'blur'
    }
  ],
});
const props = defineProps({
  addBool: Number,
});
// 表单数据
const form = reactive({
  customerId: '',
  customerName: '',
  school: '',
  speciality: '',
  money: '',
  deposit: '',
  completedMoney: '',
  director: '',
  followUp: '',
  check: '',
  degree: '',
  accountPassword: '',
  website: '',
  reviewTime: [],
  headlineTime: [],
  firstTime: [],
  finalizeTime: [],
  thesisTitle: '',
  difficulty: '',
  notes: '',
  filePath: '',
  fileName:''
});
const emit = defineEmits(['addrefClick']);
// 取消
const cancellClick = () => {
  const obj = {
    customerId: '',
    customerName: '',
    school: '',
    speciality: '',
    money: '',
    deposit: '',
    completedMoney: '',
    director: '',
    followUp: '',
    check: '',
    degree: '',
    accountPassword: '',
    website: '',
    reviewTime: [],
    headlineTime: [],
    firstTime: [],
    finalizeTime: [],
    thesisTitle: '',
    difficulty: '',
    notes: '',
    filePath: '',
    fileName:''
  }
  Object.assign(form,obj);
  emit('addrefClick', 1);
};
const uploadRef = ref(null);
// 定义负责人数组字段
const directorList = reactive([])
// 定义跟进人数组字段
const followUpList = reactive([])
// 1.执行获取负责人写手信息接口
const userFun = async()=>{
  const { data } = await getUserList({"userdepartment":"销售"});
  console.log(data);
  Object.assign(directorList,data);
}
// 1.执行获取负责人写手信息接口
const user2Fun = async()=>{
  const { data } = await getUserList({"userdepartment":"写手"});
  console.log(data);
  Object.assign(followUpList,data);
}
onMounted(()=>{
  userFun();
  user2Fun();
})
// 上传失败后的处理 
const handleError = (error, file, fileList) => { 
  console.error(error); 
  ElNotification({
    title: "文件上传",
    message: "文件上传失败",
    type: "error",
    duration: 1000
  })
}; 
// 限制只能上传一个文件
const handleExceed = (files, fileList)=>{
  ElNotification({
    title: "文件上传",
    message: "只允许上传一个文件",
    type: "error",
    duration: 2000
  })
}
const fileList = reactive([{
  name:"",
  url:""
}]);
// 文件列表删除触发
const handleRemove = (file, uploadFiles) => {
  fileList[0].name = "";
  fileList[0].url = "";
}
// 监听上传时触发
const handleChange = (files)=>{
  fileList[0].name = files.name;
}
// 上传成功后的处理 
const handleSuccess = async(response, file, fileList) => {
  form.filePath = response.data.filepath;
  form.fileName = response.data.filename;
  uploadFileFun()
// 可以在这里处理服务器返回的数据 
}; 
// 新增提交 
const uploadFile = (formEl) => { 
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    if(!fileList[0].name){
      uploadFileFun()
      return;
    }
    const filePath= await uploadRef.value.submit()
  })
};
// 封装新增调接口
const uploadFileFun = async()=>{
  const data = await uploadImg(form); 
    if(data.code == 200){
      cancellClick();
      ElNotification({
        title: "新增客户",
        message: "客户新增成功",
        type: "success",
        duration: 1000
      });
    }else{
      ElNotification({
        title: "新增客户",
        message: "客户新增失败",
        type: "error",
        duration: 1000
      });
    }
}
</script>

<style lang="scss" scoped>
.management {
  .form-buttons {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  .upload-demo {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .el-form-item {
    margin-bottom: 15px;
  }

  .el-col {
    padding: 0 10px;
  }
}
</style>